import { getPhone, setUserLogin, getUserInfo, userRelated, wxUserInfo, aliPayUserInfo, getAiliPayUserInfo } from '@/api/user'
import '@/api/user/types'
import Taro from '@tarojs/taro'
import { isSessionKey, userInfoAuth, getAuthCode } from '@/utils/auth'
import { UPDATA_USERINFO, IS_USERINFO } from './action-types'

// 微信小程序 获取用户信息
export const getAccessId = (params?) => {
  return async dispatch => {
    try {
      if (Taro.getStorageSync('logout')) return
      // 获取用户授权 return true成功获取/false获取失败
      const userStatus = await userInfoAuth()
      if (userStatus) {
        let userMsg
        if (!params) {
          // 获取用户信息。
          userMsg = await Taro.getUserInfo()
        } else {
          userMsg = params
        }
        // const isFromScene:boolean = !!Taro.getStorageSync('STORE_QRCODE')
        const sessionKey = await isSessionKey()
        const { encryptedData, iv } = userMsg
        // 调取接口3，拿到userId,如果是新用户直接走登录流程，如果userId大于0
        // 调取接口1，拿到用户信息
        // 拿到用户信息只有，记录起来即可以
        const info = await wxUserInfo({
          encryptedData,
          iv,
          sessionKey,
          // scene: isFromScene
        })
        let userInfo = info.data.data
        let { userId } = userInfo
        console.log('userInfo', info)
        // Taro.setStorageSync(IS_USERINFO, userInfo)
        //   dispatch({
        //       type: UPDATA_USERINFO,
        //       userInfo
        //   })
        // let {userId} = info.data.data
        if (userId) {
          console.log('有userId')
          Taro.setStorageSync(IS_USERINFO, userInfo)
          dispatch({
            type: UPDATA_USERINFO,
            userInfo
          })
        }
      }
    } catch (e) {
      console.log(e)
    }
  }
}


// 支付宝小程序 获取用户信息
export const getAliPayAccessId = () => {
  return async dispatch => {
    try {
      // 获取用户授权 return true成功获取/false获取失败
      await getAuthCode()
      let authCode = Taro.getStorageSync('AUTH_CODE')
      if (authCode) {
        let userInfo = Taro.getStorageSync(IS_USERINFO) || {}
        if (userInfo.userId) {
          Taro.setStorageSync(IS_USERINFO, userInfo)
          dispatch({
            type: UPDATA_USERINFO,
            userInfo
          })
        }
      }
    } catch (e) {
      console.log(e)
    }
  }
}

// 获取用户手机号
export const aliPayUserAuth = (data) => {
  return async dispatch => {
    let userInfo: any
    userInfo = {}
    console.log('有没有及你来啊啊啊啊-----data', data)
    let { mobile, aliPayUserId } = data
    // 优先把鉴权信息存在本地，给获取用户信息鉴权使用
    // 获取用户信息
    try {
      const result = await getAiliPayUserInfo({
        mobile,
        aliPayUserId
      })
      const isUserInfo = result.data.data
      userInfo = {
        ...isUserInfo,
        serverTime: +new Date(result.header['date']) / 1000
      }
      console.log('支付宝----', isUserInfo)
      // 鉴权信息与用户信息合并更新本地存储数据
      Taro.setStorageSync(IS_USERINFO, userInfo)
      const useData = await getUserInfo({
        userId: userInfo.userId
      })
      userInfo.mobile = useData.data.data.mobile
      console.log('newData',)
      Taro.setStorageSync(IS_USERINFO, userInfo)

      dispatch({
        type: UPDATA_USERINFO,
        userInfo
      })
      const backRoute = Taro.getStorageSync('BACK_ROUTE')
      if (backRoute) {
        Taro.reLaunch({
          url: '/' + backRoute
        })
        Taro.removeStorageSync('BACK_ROUTE')
        return false
      }
      if (userInfo.accessId) {
        Taro.switchTab({
          url: '/pages/tabbar/user/index'
        })
      }
    } catch (e) {
      console.log(e)
    }
  }
}

// 获取用户手机号
export const userAuth = (params: GetPhoneTypes | any) => {
  return async dispatch => {
    let userInfo: any
    let info: any
    userInfo = Taro.getStorageSync(IS_USERINFO)
    console.log('获取用户手机号 userInfo', userInfo)
    if (params.hasOwnProperty('encryptedData')) {
      // 微信授权登录方式获取用户信息
      const sessionKey = await isSessionKey()
      try {
        info = await getPhone({
          sessionKey,
          ...params
        })
        if (userInfo) {
          userInfo = {
            ...userInfo,
            ...info.data.data
          }
        } else {
          userInfo = info.data.data
        }
        Taro.setStorageSync(IS_USERINFO, userInfo)
        Taro.removeStorageSync('REGISTER_DATA')
        dispatch({
          type: UPDATA_USERINFO,
          userInfo
        })
      } catch (e) {
        console.log(e)
      }
    } else {
      console.log('执行这儿了吗---------------------')
      // 通过输入手机号、验证码方式登录
      info = await setUserLogin(params)
      if (userInfo) {
        userInfo = {
          ...userInfo,
          ...info.data.data
        }
      } else {
        userInfo = info.data.data
      }
    }
    // 优先把鉴权信息存在本地，给获取用户信息鉴权使用
    Taro.setStorageSync(IS_USERINFO, Object.assign(userInfo, {
      serverTime: +new Date(info.header['Date']) / 1000
    }))
    // 获取用户信息
    try {
      if (!userInfo) return
      const result = await getUserInfo({
        userId: userInfo.userId
      })
      const isUserInfo = result.data.data
      // // 合并用户信息
      userInfo = {
        ...userInfo,
        ...isUserInfo
      }
      const storeQrcode = Taro.getStorageSync('STORE_QRCODE') || ''
      if (storeQrcode) {
        // 用于门店与用户建立关系
        const openid = Taro.getStorageSync('IS_OPENID')
        userRelated({
          openid,
          mobile: userInfo.mobile,
          unionid: userInfo.unionid
        }).then(res => {
          console.log(res)
        }).catch(err => {
          console.log(err)
        })
      }
      // 鉴权信息与用户信息合并更新本地存储数据
      Taro.setStorageSync(IS_USERINFO, userInfo)
      console.log('有没有执行到这里来---', userInfo)
      dispatch({
        type: UPDATA_USERINFO,
        userInfo
      })
      Taro.removeStorageSync('logout')
      const backRoute = Taro.getStorageSync('BACK_ROUTE')
      if (backRoute) {
        Taro.reLaunch({
          url: '/' + backRoute
        })
        // if (backRoute.indexOf('tabbar') > -1) {
        //     Taro.reLaunch({
        //         url: '/' + backRoute
        //     })
        // } else {
        //     // 关闭当前页面，跳转到应用内的某个页面
        //     Taro.redirectTo({
        //         url: '/' + backRoute
        //     })
        // }
        Taro.removeStorageSync('BACK_ROUTE')
        return false
      }
      if (userInfo.accessId) {
        Taro.switchTab({
          url: '/pages/tabbar/user/index'
        })
      }
    } catch (e) {
      console.log(e)
    }
  }
}
// todo
export const updateAvatar = (userInfo: object) => {
  return dispatch => {
    // 更新用户信息头像
    Taro.setStorageSync(IS_USERINFO, userInfo)
    // 这里可新增更新头像接口
    dispatch({
      type: UPDATA_USERINFO,
      userInfo
    })
  }
}

// todo
export const clearUserInfo = () => {
  return dispatch => {
    // 清空用户信息
    dispatch({
      type: UPDATA_USERINFO,
      userInfo: {}
    })
  }
}
